const mariadb = require('mariadb')
const {dbpool} = require('./config.js')
const R = require('ramda')

const pool = mariadb.createPool(dbpool)

const fields = [
    'bondcode', 'sname', 'swapscode', 'securityshortname', 'startdate', 
    'listdate', 'swapprice', 'aissuevol', 'swapsdate', 'swapedate',
    'creditrating', 'partiesfname', 'frstvaluedate', 'lastvaluedate',
    'mrtydate', 'ratedes'
]

const insert = convertible => {
    const sql = 'insert into convertible (' + fields.join(',') + ') ' +
        'values (' + R.repeat('?', fields.length).join(',') + ')'
    return pool.query(sql, R.props(fields, convertible))
}

const findOne = bondcode => {
    const sql = `
        select ${fields.join(',')} from convertible 
        where bondcode = ?
    `
    return pool.query(sql, bondcode).then(R.head)
}

const updateSwapPrice = ({bondcode, swapprice}) => {
    const sql = 'update convertible set swapprice = ? where bondcode = ?'
    return pool.query(sql, [swapprice, bondcode])
}

const exists = ({bondcode}) => {
    const sql = 'select id from convertible where bondcode = ?'
    return pool.query(sql, bondcode)
        .then(res => new Promise((resolve, reject) => {
            res.length === 1 ? resolve(true) : reject('no convertible')
        }))
}

const insertOrUpdate = convertible => R.pipe(
    exists,
    R.andThen(R.thunkify(updateSwapPrice)(convertible)),
    R.otherwise(R.thunkify(insert)(convertible))
)(convertible)

const lastHistoryDate = ({bondcode}) => {
    const sql = `
        select max(date) maxdate from convertible_history 
        where bondcode = ?
    `
    return pool.query(sql, bondcode)
        .then(R.pipe(R.head, R.prop('maxdate'), R.defaultTo(new Date('1900-01-01'))))
}
    
const insertHistory = (bondcode, history) => {
    const hfields = [
        'bondcode', 'date', 'closeprice',
        'pureliability', 'swapprice', 
        'liabilitypremium', 'swappremium'
    ]
    const sql = `
        insert into convertible_history (${hfields.join(',')}) 
        values (${R.repeat('?', hfields.length).join(',')})
    `
    lastHistoryDate({bondcode}).then(lastDate => {
        let validHistory = R.pipe(
            R.filter(R.pipe(R.prop('date'), R.lt(lastDate))),
            R.map(R.assoc('bondcode', bondcode))
        )(history)
        console.log('bondcode:' + bondcode + ' insert ' + validHistory.length + ' records.')
        return pool.batch(
            sql,
            validHistory.map(R.props(hfields))
        )
    })
}

module.exports = {
    insert, findOne, updateSwapPrice, exists,
    insertOrUpdate, lastHistoryDate, insertHistory
}
